package com.chuangsi.project.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.chuangsi.common.exception.ServiceException;
import com.chuangsi.common.utils.Assert;
import com.chuangsi.common.utils.PageUtils;
import com.chuangsi.common.utils.SecurityUtils;
import com.chuangsi.project.admin.domain.Agreement;
import com.chuangsi.project.admin.domain.Brand;
import com.chuangsi.project.admin.domain.ModelTable;
import com.chuangsi.project.admin.domain.Seal;
import com.chuangsi.project.admin.dto.admin.product.*;
import com.chuangsi.project.admin.dto.app.product.*;
import com.chuangsi.project.admin.dto.common.SelectDto;
import com.chuangsi.project.admin.service.*;
import com.chuangsi.project.admin.domain.Product;
import com.chuangsi.project.system.mapper.ProductMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-03-23
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private AgreementService agreementService;
    @Autowired
    private SealService sealService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private UserProductService userProductService;

    @Override
    public List<ReqProductSelectDto> productSelect() {
        return baseMapper.productSelect().stream().peek(x->{
            if(StrUtil.isNotBlank(x.getType())){
                if(x.getType().equals("1")){
                    x.setType("原厂代销");
                }
                if(x.getType().equals("2")){
                    x.setType("其他代销");
                }
                if(x.getType().equals("3")){
                    x.setType("传统");
                }
            }
            if(StrUtil.isNotBlank(x.getPayType())){
                x.setPayType("1".equals(x.getPayType())?"全款":"分期");
            }
            if(StrUtil.isNotBlank(x.getEsignContract())){
                x.setPayType("Y".equals(x.getPayType())?"对接E签宝":"不对接E签宝");
            }
        }).collect(Collectors.toList());
    }


    @Override
    public List<ResAppProductSelectDto> getSelect(String sealId) {
        return list(Wrappers.lambdaQuery(Product.class)
                .select(Product::getProductId,Product::getProductName,Product::getEsignContract)
                .eq(StrUtil.isNotBlank(sealId),Product::getSealId,sealId))
                .stream().map(x->new ResAppProductSelectDto(x.getProductId(),x.getProductName(),x.getEsignContract()))
                .collect(Collectors.toList());

    }

    @Override
    public void productChangeStatus(String productId) {
        Product product = getById(productId);
        Assert.notNull(product,"未找到产品");
        update(Wrappers.lambdaUpdate(Product.class)
                .eq(Product::getProductId,productId)
                .set(Product::getStatus,product.getStatus().equals("1")?"2":"1"));
    }

    @Override
    public void productChangeStatusEsgin(String productId) {
        Product product = getById(productId);
        Assert.notNull(product,"未找到产品");
        if(product.getEsignContract().equals("N")){
            Seal seal = sealService.getById(product.getSealId());
            Assert.notNull(seal,"未找到印章:"+product.getSealId());
            if(StrUtil.isBlank(seal.getAppId()) ||
                    StrUtil.isBlank(seal.getAppSecret()) ||
                    StrUtil.isBlank(seal.getOrgId()) ||
                    StrUtil.isBlank(seal.getPsnId()) ||
                    StrUtil.isBlank(seal.getEsignSealId()) ){
                throw new ServiceException("印章:"+seal.getSealName()+"没有配置完整的E签宝属性，请联系系统管理员配置");
            }
        }
        update(Wrappers.lambdaUpdate(Product.class)
                .eq(Product::getProductId,productId)
                .set(Product::getEsignContract,product.getEsignContract().equals("Y")?"N":"Y"));
    }

    @Override
    public List<ResProductTreeDto> productTree(ReqProductPageDto req) {
        List<ResProductPageDto> data = baseMapper.productPage(req);
//        List<String> sealIdList = data.stream().map(ResProductPageDto::getSealId).distinct().collect(Collectors.toList());
//        if(sealIdList.isEmpty()){
//            return new ArrayList<>();
//        }
        return sealService.list().stream().map(seal->{
            ResProductTreeDto treeDto = new ResProductTreeDto();
            treeDto.setSealId(seal.getSealId());
            treeDto.setSealName(seal.getSealName());
            List<ProductTreeDto> childrens = data.stream().filter(x->x.getSealId().equals(seal.getSealId())).map(x->{
                ProductTreeDto res = new ProductTreeDto();
                BeanUtils.copyProperties(x,res);
                res.setEsignContract(x.getEsignContract());
                return res;
            }).collect(Collectors.toList());
            treeDto.setChildrens(childrens);
            return treeDto;
        }).collect(Collectors.toList());
    }



//    @Override
//    public List<ResProductPageDto> productPage(ReqProductPageDto req) {
//        return baseMapper.productPage(req);
//    }


    @Override
    public ResProductDetailDto productDetail(ReqProductDetailDto req) {
        Product product = getById(req.getProductId());
        if(product==null){
            throw new ServiceException("未查询到产品详情");
        }
        ResProductDetailDto res = new ResProductDetailDto();
        BeanUtils.copyProperties(product,res);
        Brand brand = brandService.getById(product.getBrandId());
        if(brand!=null){
            res.setBrandName(brand.getBrandName());
        }
        ModelTable modelTable = modelService.getById(product.getModelId());
        if(modelTable!=null){
            res.setModelName(modelTable.getModelName());
        }
        Agreement agreement = agreementService.getById(product.getAgreementId());
        if(agreement!=null){
            res.setAgreementName(agreement.getAgreementName());
        }
        Seal seal = sealService.getById(product.getSealId());
        if(seal!=null){
            res.setSealName(seal.getSealName());
        }
        return res;
    }


    @Override
    public List<ResAppProductListDto> pageQuery(ReqProductHotQueryDto req) {
        List<String> productIdList = userProductService.getProductIdList(SecurityUtils.getUserId());
        List<Product> productList = list(Wrappers.lambdaQuery(Product.class)
                .eq(StrUtil.isNotBlank(req.getSealId()),Product::getSealId,req.getSealId())
                .eq(Product::getStatus,"1")
                .in(!productIdList.isEmpty(),Product::getProductId,productIdList)
                .orderByDesc(Product::getVolume));
        Map<String, String> brandMap = brandService.getBrandMap();
        Map<String, String> modelMap = modelService.getModelMap();
        return productList.stream().map(m->{
            ResAppProductListDto res = new ResAppProductListDto();
            BeanUtils.copyProperties(m,res);
            res.setBrandName(brandMap.getOrDefault(m.getBrandId(),""));
            res.setModelName(modelMap.getOrDefault(m.getModelId(),""));
            return res;
        }).collect(Collectors.toList());
    }

    @Override
    public ResAppProductDetailDto productAppDetail(ReqProductDetailDto req) {
        Product product = getById(req.getProductId());
        if(product==null){
            throw new ServiceException("未查询到产品详情");
        }
        ResAppProductDetailDto res = new ResAppProductDetailDto();
        BeanUtils.copyProperties(product,res);
        Brand brand = brandService.getById(product.getBrandId());
        if(brand!=null){
            res.setBrandName(brand.getBrandName());
        }
        ModelTable modelTable = modelService.getById(product.getModelId());
        if(modelTable!=null){
            res.setModelName(modelTable.getModelName());
        }
        Agreement agreement = agreementService.getById(product.getAgreementId());
        if(agreement!=null){
            res.setSelfField(agreement.getSelfField());
            res.setAgreementDetail(agreement.getAgreementDetail());
        }
       return res;
    }

    @Override
    public List<ResAppProductListDto> productPageQuery(ReqAppProductListDto req) {
        List<String> productIdList = userProductService.getProductIdList(SecurityUtils.getUserId());
        if(!productIdList.isEmpty()){
            req.setProductIdList(productIdList);
        }
        PageUtils.startPage();
        return baseMapper.productPageQuery(req);
    }


}
